<template>
  <div class="order-detail-container">
    <el-card class="order-card" shadow="hover">
      <div class="order-header">
        <h2>订单详情</h2>
        <el-tag :type="getStatusType(order.status_display)">
          {{ order.status_display }}
        </el-tag>
      </div>

      <div class="order-content">
        <!-- 商品信息 -->
        <div class="product-section">
          <h3>商品信息</h3>
          <div class="product-info">
            <el-image 
              class="product-image" 
              :src="productImage" 
              fit="cover"
            >
              <template #placeholder>
                <div class="image-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                </div>
              </template>
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="product-details">
              <h4>{{ order.product_title || '商品已下架' }}</h4>
              <div class="price-section">
                <span class="price-label">商品价格:</span>
                <span class="price-value">¥{{ order.snapshot_price }}</span>
              </div>
              <div class="price-section">
                <span class="price-label">运费:</span>
                <span class="price-value">¥0.00</span>
              </div>
              <div class="price-section total">
                <span class="price-label">实付款:</span>
                <span class="price-value">¥{{ order.snapshot_price }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="order-info-section">
          <h3>订单信息</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="订单编号">{{ order.order_code }}</el-descriptions-item>
            <el-descriptions-item label="卖家信息">{{ order.seller_name }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatTime(order.create_time) }}</el-descriptions-item>
            <el-descriptions-item label="支付时间" v-if="order.status_display !== '已取消'">
              {{ order.payment_time ? formatTime(order.payment_time) : '未支付' }}
            </el-descriptions-item>
            <el-descriptions-item label="取消原因" v-if="order.status_display === '已取消'">
              {{ order.cancel_reason || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
      <template v-if="isSeller">
      <el-button
        type="primary"
        @click="handleShip"
        v-if="order.status_display === '待发货'"
      >
        确认发货
      </el-button>
    </template>
    <template v-else>
      <el-button 
        type="danger" 
        @click="cancelOrder" 
        v-if="order.status_display === '待支付'|| order.status_display === '待发货'"
      >
        取消订单
      </el-button>
      <el-button 
        type="primary" 
        @click="payOrder" 
        v-if="order.status_display === '待支付'"
      >
        立即支付
      </el-button>
      <el-button 
        type="success" 
        @click="confirmReceipt"
        v-if="order.status_display === '待收货'&&isSeller==false"
      >
        确认收货
      </el-button>
    </template>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, Picture } from '@element-plus/icons-vue'
import apiClient from '@/utils/request'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const DEFAULT_IMAGE = 'https://via.placeholder.com/150'
const isSeller = ref(false)

// 订单数据
const order = ref({
  order_code: '',
  product_title: '',
  snapshot_price: '0.00',
  status_display: '',
  seller_name: '',
  create_time: '',
  payment_time: null,
  cancel_reason: '',
  product_code: ''
})

// 商品图片
const productImage = ref(DEFAULT_IMAGE)





// 获取订单状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待支付': return 'warning'
    case '待发货': return ''
    case '待收货': return 'primary'
    case '已完成': return 'success'
    case '已取消': return 'danger'
    default: return 'info'
  }
}

// 格式化时间
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    const orderCode = route.params.order_code
    if (!orderCode) throw new Error('订单编号缺失')

    const response = await apiClient.get(`/api/orders/${orderCode}/`)
    const orderData = response.data

    // 设置默认值
    orderData.product_title = '商品已下架'
    productImage.value = DEFAULT_IMAGE

    if (orderData.product_code) {
      try {
        const productRes = await apiClient.get(`/api/products/buyer/${orderData.product_code}/`)
        const product = productRes.data

        // 设置商品标题
        orderData.product_title = product.name || '商品已下架'

        // 设置商品图片
        if (product.images && product.images.length > 0 && product.images[0].url) {
          const imgUrl = product.images[0].url
          // 处理相对路径
          productImage.value = imgUrl.startsWith('http') ? imgUrl : `${apiClient.defaults.baseURL}${imgUrl}`
        } else {
          productImage.value = DEFAULT_IMAGE
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
      }
    }
    order.value = orderData
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error(error.message || '加载订单详情失败')
    router.push('/orders')
  }
}

// 取消订单
const cancelOrder = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入取消原因', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '取消原因不能为空'
    })

    // 使用正确的API端点更新订单状态
    const response = await apiClient.patch(`/api/orders/${order.value.order_code}/status/`, {
      status: 4 // 4是取消状态
    },{headers: { 'Content-Type': 'application/json' }})

    // 更新取消原因
    await apiClient.patch(`/api/orders/${order.value.order_code}/`, {
      cancel_reason: reason
    },{headers: { 'Content-Type': 'application/json' }})

    await loadOrderDetail() // 重新加载订单详情
    ElMessage.success('订单已取消')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

// 支付订单
const payOrder = async () => {
  try {
    await ElMessageBox.confirm('确认支付该订单吗?', '支付确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await apiClient.post(`/api/orders/${order.value.order_code}/pay/`, {
      status: 1,
      snapshot_price: order.value.snapshot_price
    },{headers: { 'Content-Type': 'application/json' }})

    if (response.data && response.data.status === 'success') {
      await loadOrderDetail()
      ElMessage.success('支付成功')
    } else {
      throw new Error(response.data?.message || '支付失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error(error.message || '支付失败')
    }
  }
}
const handleShip = async () => {
  try {
    await ElMessageBox.confirm('确认发货吗?', '发货确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await apiClient.patch(`/api/orders/${order.value.order_code}/status/`, {
      status: 2 // 2是待收货状态
    },{headers: { 'Content-Type': 'application/json' }})

    await loadOrderDetail()
    ElMessage.success('发货成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发货失败')
    }
  }
}
// 确认收货
const confirmReceipt = async () => {
  try {
    await ElMessageBox.confirm('确认收到商品了吗?', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await apiClient.post(`/api/orders/${order.value.order_code}/complete/`, {
      status: 4 // 假设4是已完成状态
    },{headers: { 'Content-Type': 'application/json' }})

    if (response.data && response.data.status === 'success') {
      await loadOrderDetail()
      ElMessage.success('确认收货成功')
    } else {
      throw new Error(response.data?.message || '确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error(error.message || '确认收货失败')
    }
  }
}

// 初始化加载订单详情
onMounted(async() => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  const fromPath = route.query.from
  
  isSeller.value = fromPath === '/Mine/maichu'
 
  console.log('订单信息:', {
    status: order.value.status_display,
    isSeller: isSeller.value
  })
  await loadOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.order-card {
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color);
}

.order-content {
  padding: 0 20px;
}

.product-section, .order-info-section {
  margin-bottom: 30px;
}

.product-info {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.product-image {
  width: 150px;
  height: 150px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error, .image-loading {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
}

.image-error {
  color: var(--el-text-color-placeholder);
}

.product-details {
  flex: 1;
}

.price-section {
  margin: 10px 0;
  font-size: 16px;
}

.price-section.total {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-top: 20px;
}

.price-label {
  margin-right: 10px;
}

.action-buttons {
  margin-top: 30px;
  text-align: right;
}

.el-descriptions {
  margin-top: 15px;
}
</style>